<?php

namespace app\admin\controller\dealer;

use app\admin\logic\statistics\MoneyStatistics;
use app\admin\model\Admin;
use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;
use think\Validate;

/**
 * 经销商
 *
 * @icon fa fa-circle-o
 */
class Dealer extends Backend
{
    
    /**
     * Dealer模型对象
     * @var \app\admin\model\dealer\Dealer
     */
    protected $model = null;
    protected $modelValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dealer\Dealer;
        $this->view->assign("dealerTypeList", $this->model->getDealerTypeList());
        Hook::add('admin_auth','app\\admin\\behavior\\AdminAuth');
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        $statisticsModel = model('statistics');
        //总应发
        $dealermoney = $statisticsModel->dealerAmount();
        //总佣金
        $dealermoneyamount = MoneyStatistics::instance()->getDealerMoney();
        //众包费总笔数
        $zbtask_money_count = $statisticsModel->zbtaskMoneyCount(0, 0);
        //总推广
        $dealer_company_count = $statisticsModel->countCompany();
        //累计提现
        $dealer_withdraw_amount = model('admin/dealer/MoneyLog')->getWithdrawAmount();
        //经销商余额
        $dealer_usermoney = model('admin/dealer/Dealer')->sum('usermoney');

        $this->assign('dealermoney', $dealermoney);
        $this->assign('dealermoneyamount', $dealermoneyamount);
        $this->assign('zbtask_money_count', $zbtask_money_count);
        $this->assign('dealer_company_count', $dealer_company_count);
        $this->assign('dealer_withdraw_amount', $dealer_withdraw_amount);
        $this->assign('dealer_usermoney', $dealer_usermoney);

        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $row) {
                //获取管理员账号id
                $admin_id = Db::name('admin')->where(['type' => 2, 'type_id'=> $row['id']])->value('id');
                $row['admin_id'] = $admin_id;
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $dealerData = $this->model->toArray();
                    $dealerData['type'] = 2; //企业类别
                    //生成账号 加入权限组
                    Hook::listen('admin_auth',$dealerData);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**修改管理员账号*/
    public function editAdmin($ids = null) {
        $admin = new Admin();
        $row = $admin->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                if ($params['password']) {
                    if(!Validate::is($params['password'], '\S{6,16}')){
                        $this->error(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                    'username' => 'require|regex:\w{3,12}|unique:admin,username,' . $row->id,
                    'email'    => 'email|unique:admin,email,' . $row->id,
                    'password' => 'regex:\S{32}',
                ]);
                $result = $row->validate('Admin.edit')->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                $this->success();
            }
            $this->error();
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
